package com.xxh.dasongapp.security.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxh.dasongapp.config.RestTemplateConfig;
import org.apache.shiro.codec.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信请求工具类
 */
public class WechatUtil {

    private static final String appId ="wxd1565eecfe2ca777";
    private static final String secret ="9a5716f5abf5aab9e7c2e9528a09d9a8";
    private static final String authorizationCode = "authorization_code";

    private static final String requestUrl ="http://api.weixin.qq.com/sns/jscode2session";
    private static final String url = "https://api.weixin.qq.com/sns/jscode2session" +
            "?appid={appId}&secret={secret}&js_code={code}&grant_type={authorizationCode}";



    public static JSONObject getSessionKeyOrOpenId(String code) {

//        final String appId ="wxd1565eecfe2ca777";
//        final String secret ="9a5716f5abf5aab9e7c2e9528a09d9a8";
//        final String authorizationCode = "authorization_code";
//        final String requestUrl ="http://api.weixin.qq.com/sns/jscode2session";
//        final String url = "https://api.weixin.qq.com/sns/jscode2session" +
//                "?appid={appId}&secret={secret}&js_code={code}&grant_type={authorizationCode}";



        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appId", appId);
        requestUrlParam.put("secret", secret);
        requestUrlParam.put("code",code);
        requestUrlParam.put("authorizationCode",authorizationCode);


        RestTemplate restTemplate = null;
        try {
            restTemplate = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }


        JSONObject jsonObject = JSON.parseObject(restTemplate.getForObject(url, String.class, requestUrlParam));
        return jsonObject;
    }

    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionKey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSON.parseObject(result);
            }
        } catch (Exception e) {
        }
        return null;
    }
}

